<template>
  <div class="wrapper">
    <div class="header">
      <a href="javascript:void(0)" @click="backToPost" class="title">Tx | 编辑文章</a>
      <div class="right-btn-group">
        <a href="javascript:void(0)" @click="saveClick" class="r-item"><Icon type="md-filing" /></a>
        <a href="javascript:void(0)" @click="sendClick"  class="r-item"><Icon type="md-send" /></a>
        <Dropdown @on-click="dropdownClick" class="r-item" placement="bottom-end">
          <a href="javascript:void(0)"><Icon type="md-more" /></a>
          <DropdownMenu slot="list">
            <DropdownItem name="import">
              <Upload
                action="/api/markdown/upload"
                accept="application/x-zip-compressed"
                :format="['zip']"
                :before-upload="beforeUpload">
                导入Markdown
              </Upload>
            </DropdownItem>
            <DropdownItem name="export">导出Markdown</DropdownItem>
            <DropdownItem name="rollback" divided>文章回滚</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </div>
    <Row type="flex" justify="center" class="h-100">
      <transition name="slide-fade" mode="in-out">
        <Col v-if="hVisible" span="6" class="history h-100">
          <div class="h-head">
            <h4>草稿保存记录</h4>
            <a href="javascript:void(0)" @click="hVisible = false">
              <Icon type="md-close" size="20" />
            </a>
          </div>
          <ul>
            <li v-for="h in histories" :key="h.id" @click="itemClick(h)" :class="active === h.id ? 'h-item active': 'h-item'">
              <p class="h-title" v-text="h.title">这是一篇文章的标题</p>
              <div class="h-op">
                  <div class="h-time">{{ h | format}}</div>
                  <div class="h-btn">
                    <a href="javascript:void(0)" @click="resume(h)">恢复</a>
                    <a href="javascript:void(0)" @click="remove(h)" class="ml-5">删除</a>
                  </div>
              </div>
            </li>
            <li v-if="histories.length === 0" class="h-item">
              <p class="h-no-data">暂无数据</p>
            </li>
          </ul>
        </Col>
      </transition>
      <Col span="18" class="editor h-100">
        <div class="title w-100">
          <input v-model="draft.title" placeholder="输入文章标题"  class="w-100 input" />
        </div>
        <div class="brief">
          <Input v-model="draft.brief" maxlength="250" show-word-limit type="textarea"  placeholder="输入文章摘要信息" class="w-100" />
        </div>
        <Row style="margin: 1.2rem 0; border: 1px solid #ccc; padding: 0.8rem; border-radius: .5rem;" :style="{ 'z-index': zIndex}">
          <Col span="12">
            <span style="margin-right: 1.2rem;">选择分类:</span>
            <div class="mt-1">
              <Select v-model="draft.categoryId" style="width:200px;">
                <Option v-for="item in categories" :value="item.id" :key="item.id">{{ item.category }}</Option>
              </Select>
            </div>
          </Col>
          <Col span="12">
            <span style="margin-right: 1.2rem">选择标签:</span>
            <div class="mt-1">
              <Tag checkable color="#838B8B" :checked="tag.checked" @on-change="tagChange" v-for="tag in dTags" :key="tag.id" :name="tag.id"># {{tag.name}}</Tag>
            </div>
            <div class="mt-1">
              <input v-model="newTag" class="input" style="margin-right: 1.2rem" />
              <Button icon="ios-add" type="dashed" size="small" @click="handleTagAdd">添加标签</Button>
            </div>
          </Col>
          <Col span="24">
            <span>文章短链接</span>
            <Input v-model="draft.shortLink">
              <span slot="prepend">http://yourdomain.com/s/</span>
            </Input>
          </Col>
        </Row>
        <mavon-editor class="md" style="min-height: 600px; z-index: 888!important;"
          ref="md"
          :toolbars="option"
          @save="saveClick"
          @imgAdd="addImage"
          @fullScreen="fullScreen"
          v-model="draft.content"
        />
      </Col>
    </Row>
  </div>
</template>
<style scoped lang="sass">
  @import "../styles/markdown.sass"
</style>
<script>
import { Row, Col, Icon, Dropdown, DropdownMenu, DropdownItem, Input, Select, Option, Tag, Button, Upload } from 'view-design'

import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

import drafts from '../service/drafts'
import category from '../service/category'
import tag from '../service/tag'
import posts from '../service/posts'
import utils from '../utils'

export default {
  components: {
    Row,
    Col,
    Icon,
    Dropdown,
    DropdownMenu,
    DropdownItem,
    Input,
    Select,
    Option,
    Tag,
    Button,
    Upload,
    mavonEditor
  },
  props: {
    // 草稿ID
    id: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      newTag: '',
      active: 0,
      zIndex: 999,
      hVisible: false,
      draft: {
        id: 0,
        postId: 0,
        title: '',
        brief: '',
        categoryId: 0,
        tagIds: [],
        shortLink: '',
        content: ''
      },
      histories: [],
      categories: [],
      tags: [],
      option: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        navigation: true, // 导航
        save: true, // 保存
        subfield: true, // 单双栏模式
        preview: true, // 预览
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true // 帮助
      }
    }
  },
  methods: {
    beforeCheck (callback) {
      if (!this.draft.shortLink) {
        this.$Message.error('短链接必须填写')
        return
      }
      if (!this.draft.categoryId) {
        this.$Message.error('请选择分类')
        return
      }
      if (!this.draft.content) {
        this.$Message.error('请输入文章内容')
        return
      }
      posts.check(this.draft.postId, this.draft.shortLink).then(callback).catch(reason => {
        this.$Message.error(reason.message)
      })
    },
    saveClick (value) {
      this.beforeCheck(() => {
        drafts.save({ ...this.draft }).then((resp) => {
          this.$Message.success('草稿保存成功')
          this.history(this.draft.postId)
        }).catch((resp) => {
          this.$Message.error(resp.message)
        })
      })
    },
    sendClick () {
      this.beforeCheck(() => {
        drafts.publish({ ...this.draft }).then((resp) => {
          this.$Message.success('发布成功')
          this.history(this.draft.postId)
        }).catch((resp) => {
          this.$Message.error(resp.message)
        })
      })
    },
    dropdownClick (name) {
      if (name === 'import') {
        // 文件上传
      } else if (name === 'export') {
        window.location.href = '/api/markdown/export/' + this.draft.id
      } else {
        this.hVisible = !this.hVisible
      }
    },
    itemClick (item) {
      this.active = item.id
    },
    fullScreen (status) {
      if (status) {
        this.zIndex = 666
      } else {
        this.zIndex = 999
      }
    },
    beforeUpload (file) {
      const type = file.type
      if (type.indexOf('application/x-zip-compressed') < 0 && type.indexOf('application/zip') < 0) {
        this.$Message.error('请选择zip压缩文件')
      }
      // 手动处理
      const param = new FormData()
      param.append('file', file)
      const config = {
        // 添加请求头
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      this.$request.post('/api/markdown/import', param, config).then((resp) => {
        this.draft.content = resp.data
      }).catch((resp) => {
        this.$Message.error(resp.message || '文件上传失败')
      })
      return false
    },
    tagChange (checked, name) {
      const t = this.tags.filter(it => it.id === name)[0]
      if (checked) { // add
        if (this.draft.tagIds.indexOf(t.id) < 0) {
          this.draft.tags.push(t)
          this.draft.tagIds.push(t.id)
        }
      } else { // del
        if (this.draft.tagIds.indexOf(t.id) > -1) {
          this.draft.tags = this.draft.tags.filter(it => it.id !== name)
          this.draft.tagIds = this.draft.tagIds.filter(it => it !== name)
        }
      }
    },
    handleTagAdd () {
      const nt = this.newTag
      if (!nt) return
      if (this.tags.filter(t => t.name === nt).length) {
        this.$Message.error('标签已经存在')
        return
      }
      // do add
      tag.create(nt).then((resp) => {
        const t = resp.data
        this.draft.tags.push(t)
        this.draft.tagIds.push(t.id)
        this.tags.push(t)
        this.newTag = ''
      }).catch((resp) => {
        this.$Message.error(resp.message || '创建失败')
      })
    },
    addImage (pos, file) {
      console.log(pos, file)
      this.doUpload(pos, file)
    },
    doUpload (pos, file) {
      const param = new FormData()
      param.append('file', file)
      const config = {
        // 添加请求头
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      const $vm = this.$refs.md
      this.$request.post('/api/qiniu/upload', param, config).then((resp) => {
        $vm.$img2Url(pos, resp.data)
      }).catch((resp) => {
        this.$Message.error(resp.message || '文件上传失败')
      })
    },
    history (postId) {
      drafts.history(postId).then((resp) => {
        this.histories = resp.data || []
      }).catch((resp) => {
        this.$Message.error(resp.message)
      })
    },
    backToPost () {
      this.$router.replace('/post')
    },
    remove (row) {
      // 删除确认
      this.$Modal.confirm({
        title: '确认删除？',
        content: '<p>删除后你可重新添加</p>',
        onOk: () => {
          drafts.remove(row.id).then(() => {
            this.$Message.success('操作成功')
            this.history(this.draft.postId)
          }).catch((resp) => {
            this.$Message.error(resp.message)
          })
        },
        onCancel: () => {
          // this.$Message.info('Clicked cancel');
        }
      })
    },
    resume (row) {
      if (row.id !== this.draft.id) {
        this.load(row.id)
      }
    },
    load (id, post) {
      let promise
      if (post) {
        promise = drafts.getByPostId(id)
      } else {
        promise = drafts.get(id)
      }
      promise.then((resp) => {
        this.draft = resp.data
        if (this.draft.tags) {
          this.draft.tagIds = this.draft.tags.map(t => t.id)
        }
        this.history(resp.data.postId)
      }).catch((resp) => {
        this.$Message.error(resp.message)
      })
    }
  },
  computed: {
    dTags () {
      const arr = [...this.tags]
      // this.draft.tag
      for (const a of arr) {
        a.checked = this.draft.tagIds.indexOf(a.id) > -1
      }
      return arr
    }
  },
  filters: {
    format (item) {
      return utils.formatDate(item.createdAt)
    }
  },
  created () {
    this.load(this.id, 1)

    category.getAll().then((resp) => {
      this.categories = resp.data || []
    })

    tag.getAll().then((resp) => {
      this.tags = resp.data || []
    })
  }
}
</script>
